#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <unistd.h>
#include <fcntl.h>

char buf[500000];

int main() {
	int ntowrite, nwrite;
	char* ptr;
	int flag;

	ntowrite = read(STDIN_FILENO, buf, sizeof(buf));
	fprintf(stderr, "read %d bytes\n", ntowrite);

	flag = fcntl(STDOUT_FILENO, F_GETFL);
	flag |= O_NONBLOCK;
	fcntl(STDOUT_FILENO, F_SETFL, &flag);

	ptr = buf;
	while (ntowrite > 0) {
		errno = 0;
		nwrite = write(STDOUT_FILENO, ptr, ntowrite);
		fprintf(stderr, "nwrite = %d, errno = %d %s\n", nwrite, errno, strerror(errno));

		if (nwrite > 0) {
			ptr += nwrite;
			ntowrite -= nwrite;
		}
	}

	return 0;
}